/**
 * uifuture.com
 * Copyright (C) 2013-2018 All Rights Reserved.
 */
package com.netty.client;


import com.netty.message.MessageDecoder;
import com.netty.message.MessageEncoder;

import com.netty.protobuf.ProtobufDecoder;
import com.netty.protobuf.ProtobufEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @author
 */
@Component
public class NettyClient {

    public void start()  throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .remoteAddress(new InetSocketAddress("127.0.0.1", 8081))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));
                            //传输实体类数据
                            pipeline.addLast(new ProtobufEncoder());
                            pipeline.addLast(new ProtobufDecoder());
                            //传输字符窜数据
//                            pipeline.addLast(new StringEncoder(Charset.defaultCharset()));
//                            pipeline.addLast(new StringDecoder(Charset.defaultCharset()));
                            //传输自定义协议数据
                            //这里使用自定义分隔符
//                            pipeline.addLast(new MessageEncoder());
//                            pipeline.addLast(new MessageDecoder());
                            pipeline.addLast(new ClientChannelHandler());
                        }
                    });

            // 异步操作
            ChannelFuture future = null;
            // netty 启动时如果连接失败，会断线重连sync();
            future  = bootstrap.connect().addListener(new ConnectionListener()).sync();
            // 关闭客户端
            future.channel().closeFuture().sync();
        } finally {
            //优雅关闭
           group.shutdownGracefully().sync();
        }
    }
}
